package com.example.demo.domain.service;

import com.example.demo.domain.model.User;
import com.example.demo.domain.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class UserService {

    private final UserRepository userRepository;

    public User createUser(String username, String email, String password) {
        // 检查用户名是否已存在
        if (userRepository.findByUsername(username).isPresent()) {
            throw new IllegalArgumentException("Username already exists");
        }
        // 检查邮箱是否已存在
        if (userRepository.findByEmail(email).isPresent()) {
            throw new IllegalArgumentException("Email already exists");
        }
        // 创建用户并验证
        User user = new User(username, email, password);
        user.validate();
        return userRepository.save(user);
    }

    public Optional<User> getUserById(Long id) {
        return userRepository.findById(id);
    }

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    public User updateUser(Long id, String username, String email) {
        User user = userRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("User not found"));
        
        // 检查新用户名是否被其他用户使用
        if (!user.getUsername().equals(username)) {
            userRepository.findByUsername(username).ifPresent(u -> {
                throw new IllegalArgumentException("Username already exists");
            });
        }
        
        // 检查新邮箱是否被其他用户使用
        if (!user.getEmail().equals(email)) {
            userRepository.findByEmail(email).ifPresent(u -> {
                throw new IllegalArgumentException("Email already exists");
            });
        }
        
        user.update(username, email);
        user.validate();
        return userRepository.save(user);
    }

    public void deleteUser(Long id) {
        if (!userRepository.findById(id).isPresent()) {
            throw new IllegalArgumentException("User not found");
        }
        userRepository.deleteById(id);
    }
}